#include "stdafx.h"
#include "LuaManager.h"

using namespace unigame;

LuaManager* LuaManager::m_instance = 0;

int onLuaMessage(lua_State* ls);

LuaManager::~LuaManager()
{
	unloadAll();
}

void LuaManager::unloadAll()
{
	for(std::map<std::string, LuaScript*>::iterator it = m_scripts.begin(); it != m_scripts.end(); ++it)
	{
		it->second->release();
	}
	m_scripts.clear();
	m_states.clear();
}

void LuaManager::unloadScript(const char* name)
{
	std::string str = name;
	std::map<std::string, LuaScript*>::iterator it = m_scripts.find(str);
	if(it != m_scripts.end())
	{
		it->second->release();
		m_scripts.erase(it);
	}
}

LuaScript* LuaManager::loadScript(const char* name)
{
	std::string str = name;
	std::map<std::string, LuaScript*>::iterator it = m_scripts.find(str);
	LuaScript* s = 0;
	if(it == m_scripts.end())
	{
		s = uni_new LuaScript(name);
		m_scripts[str] = s;
		m_states[s->state()] = s;
		lua_register(s->state(), "sendMessage", onLuaMessage);
	}
	else
	{
		s = it->second;
	}
	s->retain();
	return s;
}

LuaScript* LuaManager::getScript(const char* name)
{
	std::map<std::string, LuaScript*>::iterator it = m_scripts.find(name);
	if(it != m_scripts.end())
	{
		return it->second;
	}
	return 0;
}

LuaScript* LuaManager::getScript(lua_State* ls)
{
	std::map<lua_State*, LuaScript*>::iterator it = m_states.find(ls);
	if(it != m_states.end())
	{
		return it->second;
	}
	return 0;
}

int onLuaMessage(lua_State* ls)
{
	LuaScript* s = LuaManager::instance()->getScript(ls);
	std::string str;
	s->getCallbackName(&str);
	s->runCallback(str.c_str());
	return 0;
}